export function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function DateFormat(pattern) {
  this.pattern = pattern
  this.format = date => {
    var o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds() // 毫秒
    }
    let fmt = this.pattern
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  }
}

export function customizeTime(timer) {
  if (timer instanceof Date) {
    timer = timer.getTime()
  }
  const currentDate = new Date()
  const currentTime = currentDate.getTime()
  timer = Number(timer)
  const date = new Date(timer)
  const todayTimer = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()).getTime()// 今日凌晨
  const diffTime = todayTimer - timer // 和今日凌晨时刻的差
  let prefix = ''
  if (diffTime <= 0) { // 时间为今天
    const diffCurrTimer = currentTime - timer // 和当前时刻的差
    if (diffCurrTimer > 60 * 60 * 1000) { // 一个小时以上
      const diffHour = (-diffTime) / (60 * 60 * 1000).toFixed(2)
      if (diffHour <= 5) {
        prefix = '凌晨'
      } else if (diffHour <= 8) {
        prefix = '早晨'
      } else if (diffHour <= 11) {
        prefix = '上午'
      } else if (diffHour <= 13) {
        prefix = '中午'
      } else if (diffHour <= 17) {
        prefix = '下午'
      } else if (diffHour <= 18) {
        prefix = '傍晚'
      } else if (diffHour <= 24) {
        prefix = '晚上'
      }
    }
  } else if (diffTime < 86400000) { // 时间为昨天
    prefix = '昨天'
  } else if (diffTime < 86400000 * 2) { // 时间为前天
    prefix = '前天'
  } else {
    return new DateFormat('yyyy-MM-dd hh:mm').format(date)
  }
  return (prefix ? (prefix + ' ') : '') + new DateFormat('hh:mm').format(date)
}

export function dateJS(date, num) {
  let time = date.getTime()
  time += num * 60 * 60 * 24 * 1000
  let newDate = new Date(time)
  return (new DateFormat('yyyy-MM-dd')).format(newDate)
}

export function dataPrivary(obj) {
  if (obj == null || obj === undefined || obj.length < 1) {
    return obj
  }
  var data = String(obj)
  // 手机号
  var PHONE_REGEXP = /^1\d{10}$/
  // 身份证号
  var CARD_REGEXP = /^\d{17}([0-9]|X)$/
  // 车牌号
  var CAR_REGEXP = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/

  if (PHONE_REGEXP.test(data)) {
    return changedata(data, 3, 7, '*')
  } else if (CARD_REGEXP.test(data)) {
    return changedata(data, 6, 14, '*')
  } else if (CAR_REGEXP.test(data)) {
    return changedata(data, 2, 5, '*')
  } else {
    return obj
  }
}

// 身份证号合法性验证
// 支持15位和18位身份证号
// 支持地址编码、出生日期、校验位验证
export function IdentityCodeValid(code) {
  var city = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江 ',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北 ',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏 ',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外 '
  }
  var tip = ''
  var pass = true

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = '身份证号格式错误'
    pass = false
  } else if (!city[code.substr(0, 2)]) {
    tip = '地址编码错误'
    pass = false
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length === 18) {
      code = code.split('')
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验位
      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
      var sum = 0
      var ai = 0
      var wi = 0
      for (var i = 0; i < 17; i++) {
        ai = code[i]
        wi = factor[i]
        sum += ai * wi
      }
      // var last = parity[sum % 11]
      if (String(parity[sum % 11]) !== String(code[17])) {
        tip = '校验位错误'
        pass = false
      }
    }
  }
  console.info(tip)
  return pass
}

export function changedata(data, start, end, str) {
  var len = data.length
  var leftStr = data.substring(0, start)
  var rightStr = data.substring(end, len)
  var s = ''
  var i = 0
  for (i = 0; i < end - start; i++) {
    s += str
  }
  return leftStr + s + rightStr
}

export function NumFormat(num) {
  const w = num.toString().indexOf('.')
  const x = (num.toString().indexOf('.') !== -1) ? num.toString().substring(0, w) : num.toLocaleString()
  const c = (num.toString().indexOf(',') !== -1) ? x.toLocaleString() : x.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  return c
}

export function dateFormat(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) {
    return ''
  }
  if (typeof date === 'string') {
    date = new Date(date.replace(/-/g, '/'))
  }
  if (typeof date === 'number') {
    date = new Date(date)
  }
  var o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  var week = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export function getUUID() {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}


/**
 * 将剩余毫秒计算出剩余天数，小时，分钟，秒
 * @param cz 剩余的毫秒数
 * @returns {string}
 */
export function getTimeLeftInfo(cz) {
  const leftsecond = parseInt(cz / 1000)
  let day = Math.floor(leftsecond / (60 * 60 * 24))
  let hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600)
  let minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60)
  let second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60)
  if (day < 10) { day = '0' + day }
  if (hour < 10) { hour = '0' + hour }
  if (minute < 10) { minute = '0' + minute }
  if (second < 10) { second = '0' + second }
  return {
    day,
    hour,
    minute,
    second
  }
}
